package com.my.okhttps.test.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ejlchina.okhttps.HttpResult;
import com.ejlchina.okhttps.OkHttps;
import com.my.core.domain.exception.ServiceException;
import com.my.okhttps.test.service.IHealthService2;
import com.my.okhttps.test.vo.vo.health2.TreatmentRecord;
import com.my.okhttps.test.vo.vo.health2.UserBaseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author timo 2021/3/18
 */
@Component
@Slf4j
public class HealthServiceImpl2 implements IHealthService2 {

    public static String DOMAIN;

    @Value("${health2.domain:https://jklz.jkluzhou.cn/}")
    public void setDOMAIN(String DOMAIN) {
        HealthServiceImpl2.DOMAIN = DOMAIN;
    }

    @FunctionalInterface
    interface DecryptFun<T> {
        T decrypt(JSONObject data);
    }

    public Object operation(Map req, String url, DecryptFun decryptFun){
        HttpResult httpResult= OkHttps.sync(DOMAIN+url)
                    .addUrlPara(req)
                    .get();
        HttpResult.Body body = httpResult.getBody();
        JSONObject jsonObject = JSON.parseObject(String.valueOf(body));
        String ret = jsonObject.getString("ret");
        if("1".equals(ret)) {
            return decryptFun.decrypt(jsonObject);
        }
        String msg = jsonObject.getString("message");
        throw new ServiceException(msg);
    }


    @Override
    public UserBaseVo getUserBaseInfo(String idCard, String username) {
        Map<String,String> req = new HashMap<String,String>(16);
        req.put("idCard", idCard);
        req.put("username", username);
        UserBaseVo operation = (UserBaseVo) operation(req, "JKLZWeChat/public/user/validate", valueData -> {
            JSONObject datas = valueData.getJSONObject("dsdata");
            return datas.toJavaObject(UserBaseVo.class);
        });
        return operation;
    }

    @Override
    public List<TreatmentRecord> getTreatmentRecord(String idcard, String stype, String orgName) {
        Map<String,String> req = new HashMap<String,String>(16);
        req.put("idcard", idcard);
        req.put("stype", stype);
        List<TreatmentRecord> data = (List<TreatmentRecord>) operation(req, "SMDP/interface/healthLuZhou/findHealthList", valueData -> {
            JSONArray datas = valueData.getJSONArray("data");
            List<TreatmentRecord> vos = datas.toJavaList(TreatmentRecord.class);
            if(StringUtils.isNotBlank(orgName)){
                vos = vos.stream().filter(x -> x.getOrgname().equals(orgName)).collect(Collectors.toList());
            }
            return vos;
        });
        return data;
    }
}
